#-*- encoding:utf-8 -*-
from django.conf import settings
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
import smtplib
import time
import random

class BadHeaderError(ValueError):
    pass

class SafeMIMEText(MIMEText):
    def __setitem__(self, name, val):
        "Forbids multi-line headers, to prevent header injection."
        if '\n' in val or '\r' in val:
            raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name)
        if name == "Subject":
            val = Header(val, settings.DEFAULT_CHARSET)
        MIMEText.__setitem__(self, name, val)
        
def sendHtmlMail(subject, message, from_email, recipient_list, 
                 fail_silently=False, auth_user=None, auth_password=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
    """
    print message
    if auth_user is None:
        auth_user = settings.EMAIL_HOST_USER
    if auth_password is None:
        auth_password = settings.EMAIL_HOST_PASSWORD
    try:
        server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
        if auth_user and auth_password:
            server.login(auth_user, auth_password)
    except:
        if fail_silently:
            return
        raise
    from_email = from_email or settings.DEFAULT_FROM_EMAIL
    msg = SafeMIMEText(message, 'html', settings.DEFAULT_CHARSET)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(recipient_list)
    msg['Date'] = formatdate()
    try:
        random_bits = str(random.getrandbits(64))
    except AttributeError: # Python 2.3 doesn't have random.getrandbits().
        random_bits = ''.join([random.choice('1234567890') for i in range(19)])
    msg['Message-ID'] = "<%d.%s@%s>" % (time.time(), random_bits, from_email)
    try:
        server.sendmail(from_email, recipient_list, msg.as_string())
    except:
        if not fail_silently:
            raise
    try:
        server.quit()
    except:
        if fail_silently:
            return
        raise